package com.eqdd.yiqidian.ui.share;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.RecyclerViewCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.SelectBean;
import com.eqdd.yiqidian.bean.rebuild.ShareConf;
import com.eqdd.yiqidian.bean.rebuild.ShareEnterConf;
import com.eqdd.yiqidian.utils.ReflectUtil;
import com.eqdd.yiqidian.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

public class ShareEnterActivity extends BaseActivity {

    private int type = -1;
    private RecyclerViewCustom dataBinding;
    private String share;
    private Uri uri;
    private ArrayList<Uri> arrayList;
    private ArrayList<SelectBean> selectBeans = new ArrayList<>();


    private int shareMode = 0;
    private SlimAdapterEx slimAdapterEx;
    private ShareEnterConf shareEnterConf;
    private Bundle bundle;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_recyclerview);
        shareEnterConf = (ShareEnterConf) getIntent().getSerializableExtra("bean");
        if (shareEnterConf == null) {
            ShareConf shareConf = new ShareConf().setTitle("请选择")
                    .setRightTitle("发送")
                    .setMaxNum(5)
                    .setMaxTip("最多%d");

            shareEnterConf = (ShareEnterConf) new ShareEnterConf()
                    .setFriendConf(shareConf)
                    .setQunChooseConf(shareConf)
                    .setQunListConf(shareConf)
                    .setQunMemberConf(shareConf)
                    .setStaffConf(shareConf)
                    .setTitle("请选择")
                    .setRightTitle("发送")
                    .setMaxNum(5)
                    .setMaxTip("最多%d");
        }
        initTopTitleBar(View.VISIBLE, shareEnterConf.getTitle());
        initTopRightText(shareEnterConf.getRightTitle(), (i) -> dealSelect());
    }

    private void dealSelect() {
        if (shareMode == ShareUtil.FROM_EQD) {
            sendMyself();
        } else if (shareMode == ShareUtil.FROM_OTHER) {
            switch (type) {
                case ShareUtil.TEXT:
                    sendText();
                    break;
                case ShareUtil.IMAGE:
                    ShareUtil.sendImg(ShareEnterActivity.this, selectBeans, uri);
                    break;

            }
        } else if (shareMode == ShareUtil.FROM_EQD_GET) {
            Intent intent = new Intent();
            intent.putParcelableArrayListExtra(Config.SELECTED_BEANS, selectBeans);
            setResult(Config.SUCCESS, intent);
            finish();
        }
    }

    private void sendMyself() {

        ShareUtil.sendMyself(this, selectBeans);
    }


    private void sendText() {
        ShareUtil.sendText(this, selectBeans, share);
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        String action = intent.getAction();
        String intentType = intent.getType();
        shareMode = (!shareEnterConf.isShare()) ? ShareUtil.FROM_EQD_GET : (AppConstent.messageContent == null ? ShareUtil.FROM_OTHER : ShareUtil.FROM_EQD);
        System.out.println(shareMode);
        if (shareMode == ShareUtil.FROM_OTHER) {
            if (Intent.ACTION_SEND.equals(action) && intentType != null) {
                if ("text/plain".equals(intentType)) {
                    dealTextMessage(intent);
                } else if (intentType.startsWith("image/")) {
                    dealPicStream(intent);
                } else {
                    ToastUtil.showShort("不支持此类型");
                    finish();
                }
            } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && intentType != null) {
                if (intentType.startsWith("image/")) {
                    dealMultiplePicStream(intent);
                }
            }
        }

        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterEx = SlimAdapterEx.create()
                .register(R.layout.list_item_07, new SlimInjector<String>() {
                    @Override
                    public void onInject(String data, IViewInjector injector) {
                        injector.text(R.id.tv_content, data);
                    }
                })
                .register(R.layout.list_item_04, new SlimInjector<SelectBean>() {
                    @Override
                    public void onInject(SelectBean data, IViewInjector injector) {
                        injector.text(R.id.tv_content, data.getContent())
                                .imageCircle(R.id.iv_head, data.getHeadImg())
                                .checked(R.id.checkbox, data.isChecked())
                                .enable(R.id.checkbox, data.isEnable())
                                .text(R.id.tv_right, data.isEnable() ? "" : shareEnterConf.getEnableTip());
                    }
                }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    if (slimAdapterEx.getData().get(position) instanceof String) {
                        switch (position) {
                            case 0:
                                bundle = new Bundle();
                                bundle.putSerializable("bean", shareEnterConf.getFriendConf());
                                startActivityForResult(ShareFriendActivity.class, bundle, Config.SHARE_FRIEND);
                                break;
                            case 1:
                                bundle = new Bundle();
                                bundle.putSerializable("bean", shareEnterConf.getFriendConf());
                                startActivityForResult(ShareWorkMateActivity.class, bundle, Config.SHARE_WORKMATE);
                                break;
                            case 2:
                                startActivityForResult(ShareQunzuListActivity.class, null, Config.SHARE_QUN_MEMBER);
                                break;
                            case 3:
                                startActivityForResult(ShareQunzuActivity.class, null, Config.SHARE_QUNZU);
                                break;
                        }
                    } else {
                        SelectBean bean = (SelectBean) slimAdapterEx.getDataItem(position);
                        if (bean.isEnable()) {
                            if (!bean.isChecked() && shareEnterConf.getMaxNum() != -1 && selectBeans.size() >= shareEnterConf.getMaxNum()) {
                                ToastUtil.showShort(String.format(shareEnterConf.getMaxTip(), shareEnterConf.getMaxNum()));
                                return;
                            }
                            bean.setChecked(!bean.isChecked());
                            if (bean.isChecked()) {
                                selectBeans.add(bean);
                            } else {
                                selectBeans.remove(bean);
                            }
                            slimAdapterEx.notifyItemChanged(position);
                        }

                    }
                });
    }

    private void refresh() {
        slimAdapterEx.getData().clear();
        slimAdapterEx.getData().add("好友");
        slimAdapterEx.getData().add("同事");
        if (shareMode != ShareUtil.FROM_EQD_GET && shareEnterConf.isAll()) {
            slimAdapterEx.getData().add("群成员");
            slimAdapterEx.getData().add("群组");
        }
        RongIM.getInstance().
                getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
                    @Override
                    public void onSuccess(List<Conversation> conversations) {
                        if (conversations != null) {
                            for (Conversation conversation : conversations) {
                                if (shareMode == ShareUtil.FROM_EQD_GET && conversation.getConversationType() == Conversation.ConversationType.GROUP) {
                                    continue;
                                }
                                String portrait;
                                String title;
                                title = conversation.getConversationTitle();
                                if (TextUtils.isEmpty(title)) {
                                    title = RongContext.getInstance().getConversationTemplate(conversation.getConversationType().getName()).getTitle(conversation.getTargetId());
                                }

                                portrait = conversation.getPortraitUrl();
                                if (TextUtils.isEmpty(portrait)) {
                                    Uri groupUserInfo = RongContext.getInstance().getConversationTemplate(conversation.getConversationType().getName()).getPortraitUri(conversation.getTargetId());
                                    portrait = groupUserInfo != null ? groupUserInfo.toString() : null;
                                }

                                SelectBean selectBean = new SelectBean();
                                if (shareEnterConf.getEnabledBeans() != null) {
                                    for (Object o : shareEnterConf.getEnabledBeans()) {
                                        if (ReflectUtil.getField(o, shareEnterConf.getGuidField()).equals(conversation.getTargetId())) {
                                            selectBean.setEnable(false);
                                            break;
                                        }
                                    }
                                }
                                selectBean.setHeadImg(portrait);
                                selectBean.setContent(title);
                                selectBean.setGuid(conversation.getTargetId());
                                selectBean.setType(conversation.getConversationType());
                                slimAdapterEx.getData().add(selectBean);
                            }
                        }
                        slimAdapterEx.notifyItemRangeChanged(0, slimAdapterEx.getData().size());

                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                        slimAdapterEx.notifyItemRangeChanged(0, slimAdapterEx.getData().size());

                    }
                });
    }


    void dealTextMessage(Intent intent) {
        share = intent.getStringExtra(Intent.EXTRA_TEXT);
        type = ShareUtil.TEXT;
    }

    void dealPicStream(Intent intent) {
        type = ShareUtil.IMAGE;
        uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
    }

    void dealMultiplePicStream(Intent intent) {
        type = ShareUtil.MULTI_IMAGE;
        arrayList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
    }

    @Override
    public void setView() {
        refresh();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            selectBeans = data.getParcelableArrayListExtra(Config.SELECTED_BEANS);
            dealSelect();
        }
    }
}
